package t05;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class TransactionProcessor {
    private List<Account> accounts;
    private File dataFile;
    private Scanner scanner;


    public TransactionProcessor(String dataFileName) {
        this.accounts = new ArrayList<Account>();
        this.dataFile = new File(dataFileName);
        // 创建该对象时，将dataFile的信息加载到accounts中
        loadFile();
    }

    /**
     * 加载dataFile文件信息
     */
    public void loadFile() {
        try {
            // 使用Scanner读取dataFile中的账户信息
            scanner = new Scanner(dataFile);
            while (scanner.hasNextLine()) {
                // 获取scanner后面一行的数据
                String line = scanner.nextLine();
                // 通过逗号将其分为包含4个字符串的数组
                String[] parts = line.split(",");
                if (parts.length == 4) {
                    accounts.add(new Account(parts[0], parts[1], parts[2], Double.parseDouble(parts[3])));
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            scanner.close();
        }
    }

    /**
     * 保存账号信息
     */
    public void saveAccount() {
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(dataFile);
            for (Account account : accounts) {
                // 将account信息写入dataFile中
                printWriter.write(account.getAccountNumber() + "," + account.getFirstName() + "," + account.getLastName() + "," + account.getBalance() + "\n");
            }
            // 刷新数据
            printWriter.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            printWriter.close();
        }

    }

    /**
     * 显示账号信息
     */
    public void displayAccount() {
        for (Account account : accounts) {
            System.out.println("Account Number: " + account.getAccountNumber() + "  First Name: " + account.getFirstName() + "  Last Name: " + account.getLastName() + "  Balance: " + account.getBalance());
        }
    }

    /**
     * 添加账号信息
     */
    public void addAccount(String accountNumber, String firstName, String lastName, Double balance) {
        Account account = new Account(accountNumber, firstName, lastName, balance);
        accounts.add(account);
        // 添加完之后保存账户信息
        saveAccount();
    }


    /**
     * 删除账号信息
     */
    public void deleteAccount(String accountNumber) {
        Iterator<Account> iterator = accounts.iterator();
        while (iterator.hasNext()) {
            Account next = iterator.next();
            if (next.getAccountNumber().equals(accountNumber)) {
                iterator.remove();
                // 假设id唯一，删除一行账号信息，就结束删除
                break;
            }
        }
        // 删除之后保存账户信息
        saveAccount();
    }

    /**
     * 更新账号信息
     */
    public void updateAccount(String accountNumber, String firstName, String lastName, Double balance) {
        for (Account account : accounts) {
            if (account.getAccountNumber().equals(accountNumber)) {
                account.setFirstName(firstName);
                account.setLastName(lastName);
                account.setBalance(balance);
            }
        }
        // 更新完之后，保存账户信息
        saveAccount();
    }

    /**
     * 把所有当前账号的格式化清单存储于一个
     * 用于打印的文本文件（printFile）中
     *
     * @param printFileName
     */
    public void printAccountToPrintFile(String printFileName) {
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(printFileName);
            // 写入首行数据
            printWriter.write("ID\tFirst Name\tLast Name\tBalance\n");
            for (Account account : accounts) {
                // 格式化字符，%s表示给一个字符串占位，%.2f表示给一个两位小数的浮点数占位，
                // 最后加\n，写入一行数据就换行
                String formattedLine = String.format("%s\t%s\t%s\t%.2f\n", account.getAccountNumber(), account.getFirstName(), account.getLastName(), account.getBalance());
                // 将 formattedLine 字符串写到 printFile 文件中
                printWriter.write(formattedLine);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            printWriter.close();
        }
    }

    /**
     * 读取 printFile 文件中的信息，
     * 并将其打印到控制台
     */
    public void readerPintFileToConsole() {
        // 创建字符流输出对象
        FileReader fileReader = null;
        try {
            fileReader = new FileReader("E:\\Myself\\Java\\task\\src\\t05\\printFile.txt");
            // 获取读取的字符数
            int read = 0;
            // 创建字符数组，用于存储数据
            char[] chars = new char[1024];
            // 读数据
            while ((read = fileReader.read(chars)) != -1) {
                String str = new String(chars, 0, read);
                // 将数据打印到控制台
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
